// pages/customer-add/customer-add.js
import http from '../../utils/http.js';
const apiConfig = require('../../utils/apiConfig.js');

Page({
  data: {
    formData: {
      customer_name: '',
      customer_phone: '',
      county: '',
      town: '',
      village: '',
      address: '',
      another_name: ''
    },
    counties: [],
    towns: [],
    villages: [],
    selectedCounty: null,
    selectedTown: null,
    selectedVillage: null,
    selectedCountyIndex: -1,
    selectedTownIndex: -1,
    selectedVillageIndex: -1
  },
  onLoad() {
    this.loadCounties();
  },
  onReady() {},
  onShow() {},
  handleSubmit(e) {
    const { customer_name, customer_phone, another_name } = this.data.formData;
    const params = {
      customer_name,
      customer_address: `${this.data.selectedCounty?.address_name || ''}${this.data.selectedTown?.address_name || ''}${this.data.selectedVillage?.address_name || ''}`,
      county: this.data.selectedCounty?.id || '',
      town: this.data.selectedTown?.id || '',
      village: this.data.selectedVillage?.id || '',
      customer_phone,
      another_name
    };
    http.request({
      url: apiConfig.addCustomer,
      method: 'POST',
      data: params,
    }).then(res => {
      if (res.status === 200) {
        wx.showToast({
          title: '添加成功',
          icon: 'success',
          duration: 2000,
          success: () => {
            wx.navigateBack({
              delta: 1
            })
          }
        })
      } else {
        wx.showToast({
          title: '添加失败',
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  // 加载县数据
  loadCounties() {
    http.request({
      url: '/api/getCounties',
      method: 'GET'
    }).then(res => {
      if (res.status === 200) {
        this.setData({
          counties: res.data.map(item => ({
            id: item.id,
            address_name: item.address_name
          }))
        }, () => {
          console.log('县数据加载完成:', this.data.counties);
        });
      }
    }).catch(err => {
      console.error('县数据加载失败:', err);
    });
  },

  // 加载镇数据
  loadTowns(provinceId) {
    http.request({
      url: '/api/getCities',
      method: 'GET',
      data: { provinceId: provinceId }
    }).then(res => {
      if (res.status === 200) {
        this.setData({
          towns: res.data,
          villages: [],
          selectedTown: null,
          selectedVillage: null
        }, () => {
          console.log(`县 ID ${provinceId} 的镇数据加载完成:`, this.data.towns);
        });
      }
    }).catch(err => {
      console.error('镇数据加载失败:', err);
    });
  },

  // 加载村数据
  loadVillages(cityId) {
    http.request({
      url: '/api/getDistricts',
      method: 'GET',
      data: { cityId: cityId }
    }).then(res => {
      if (res.status === 200) {
        this.setData({
          villages: res.data,
          selectedVillage: null
        }, () => {
          console.log(`镇 ID ${cityId} 的村数据加载完成:`, this.data.villages);
        });
      }
    }).catch(err => {
      console.error('村数据加载失败:', err);
    });
  },
  // 县选择改变
  bindCountyChange(e) {
    const index = e.detail.value;
    const selectedCounty = this.data.counties[index];
    console.log('县选择改变，选中县:', selectedCounty.address_name);
    this.setData({ selectedCounty, selectedCountyIndex: index }, () => {
      this.loadTowns(selectedCounty.id);
    });
  },

  // 镇选择改变
  bindTownChange(e) {
    const index = e.detail.value;
    const selectedTown = this.data.towns[index];
    console.log('镇选择改变，选中镇:', selectedTown.address_name);
    this.setData({ selectedTown, selectedTownIndex: index }, () => {
      this.loadVillages(selectedTown.id);
    });
  },

  // 处理输入变化
  handleInputChange(e) {
    const { field } = e.currentTarget.dataset;
    const { value } = e.detail;
    this.setData({
      [`formData.${field}`]: value
    });
  },

  // 村选择改变
  bindVillageChange(e) {
    const index = e.detail.value;
    const selectedVillage = this.data.villages[index];
    console.log('村选择改变，选中村:', selectedVillage.address_name);
    this.setData({ selectedVillage, selectedVillageIndex: index });
  },
})